<?php

namespace App\Models\Shop;

use App\Helpers\SelfEncrypt;
use App\Models\BaseModel;
use Illuminate\Http\Request;
use Ramsey\Uuid\Uuid;

class ShopGoodsModel extends BaseModel
{
    protected $table = 'shop_goods';

    protected $primaryKey = 'goods_id';

    public $dateFormat = 'U';


    public function attributes()
    {
        return $this->hasMany('App\Models\Shop\ShopGoodsAttributeModel','goods_id','goods_id');
    }

    public function type()
    {
        return $this->belongsTo('App\Models\Shop\ShopTypeModel','type_id','id');
    }

    public function specs()
    {
        return $this->hasMany('App\Models\Shop\ShopGoodsSpecModel','goods_id','goods_id');
    }

    public function sku()
    {
        return $this->hasMany('App\Models\Shop\ShopGoodsSpecValueModel','goods_id','goods_id');
    }

    public function bills()
    {
        return $this->hasOne('App\Models\Shop\ShopGoodsBillModel','goods_id','goods_id');
    }


    public function addGoods(Request $request,$zone=1)
    {
        if(!$request->post('category_ids')){
            $this->errorMsg = '请选择商品分类';
            return false;
        }
        if(!$request->post('price')){
            $this->errorMsg = '请输入商品价格';
            return false;
        }
//        if(!$request->post('vip_price')){
//            $this->errorMsg = '请输入会员价格';
//            return false;
//        }
       if(!$request->post('market_price')){
            $this->errorMsg = '请输入市场价格';
            return false;
        }
       if(!$request->post('goods_name')){
            $this->errorMsg = '请输入商品名称';
            return false;
        }
      if(!$request->post('title')){
            $this->errorMsg = '请输入商品标题';
            return false;
        }
      if(!$request->post('wp_detail')){
            $this->errorMsg = '请输入商品详情';
            return false;
        }
      if(!$request->post('goods_images')){
            $this->errorMsg = '请上传商品图片';
            return false;
        }
      if(!$request->post('stock')){
            $this->errorMsg = '请输入商品库存';
            return false;
        }
        if(!$request->post('stock_warning')){
            $this->errorMsg = '请输入预警库存';
            return false;
        }


        $goods = new self();
        $this->handPrice($request,$goods);
        $this->handleCategory($request->post('category_ids'),$goods);
        $goods->goods_name = $request->post('goods_name');
        $goods->goods_code = $this->setGoodsCode($request->post('goods_code'),$zone);
        $goods->title = $request->post('title');
        $goods->dan = $request->post('dan');
        $goods->description = $request->post('description');
        $goods->keywords = $request->post('keywords');
        $goods->wp_detail = $request->post('wp_detail');
        $goods->pc_detail = $request->post('pc_detail');
        $goods->remarks = $request->post('remarks');
        $goods->service_safe = $request->post('service_safe','无理由退货');//服务保证
        $goods->remarks = $request->post('remarks');
        $goods->unit_type = $request->post('unit_type');
        $goods->goods_images = $request->post('goods_images');
        $goods->is_recommend = $request->post('is_recommend',0);
        $goods->is_new = $request->post('is_new',1);
        $goods->is_hot = $request->post('is_hot',0);
        $goods->is_home_show = $request->post('is_home_show',0);
        $goods->user_id = $request->post('user_id',0);
        $goods->brand_id = $request->post('brand_id',0);
        $goods->store_id = $request->post('store_id',0);
        $goods->type_id = $request->post('goods_type',0);
        $goods->stock = $request->post('stock',100);
        $goods->post_type = $request->post('post_type',0);
        $goods->postage = $request->post('postage',0);
        $goods->stock_warning = $request->post('stock_warning',10);
        $goods->show_sales_volume = $request->post('show_sales_volume',100);
        $goods->sort = $request->post('sort',1000);
        $goods->xf_points_ratio = $request->post('xf_points_ratio',0);
        $goods->goods_zone = $zone;
        if(!$goods->save()){
            return false;
        }
        $res = true;
        if($zone == 1){
            $res = ShopGoodsBillModel::init()->addPrice($request,$goods->goods_id);//特惠增值区
        }
        if(!$res){
            $goods->delete();
        }
        $this->handleAttribute($request,$goods->goods_id);
        $this->handleSpec($request,$goods->goods_id);

        return $res;
    }

    public function edit(Request $request,$id)
    {
        $goods  = self::find($id);
        $this->handleCategory($request->post('category_ids'),$goods);
        $goods->goods_name = $request->post('goods_name');
        $goods->title = $request->post('title');
        $goods->dan = $request->post('dan');
        $goods->description = $request->post('description');
        $goods->keywords = $request->post('keywords');
        $goods->wp_detail = $request->post('wp_detail');
        $goods->pc_detail = $request->post('pc_detail');
        $goods->remarks = $request->post('remarks');
        $goods->service_safe = $request->post('service_safe','无理由退货');//服务保证
        $goods->remarks = $request->post('remarks');
        $goods->goods_images = $request->post('goods_images');
        $goods->user_id = $request->post('user_id',0);
        $goods->brand_id = $request->post('brand_id',0);
        $goods->store_id = $request->post('store_id',0);
        $goods->type_id = $request->post('goods_type',0);
        $goods->postage = $request->post('postage',0);
        $goods->stock = $request->post('stock',100);
        $goods->post_type = $request->post('post_type',0);
        $goods->show_sales_volume = $request->post('show_sales_volume',$goods->fact_sales_volume);
        $goods->stock_warning = $request->post('stock_warning',10);
        $goods->sort = $request->post('sort',1000);
        $goods->xf_points_ratio = $request->post('xf_points_ratio',0);
        if(!$goods->save()){
            return false;
        }
        $this->handleAttribute($request,$goods->goods_id);
        $this->handleSpec($request,$goods->goods_id);
        return true;
    }

    public function handleAttribute(Request $request,$goods_id)
    {
        if($request->post('attr_title')){
            $data['goods_id'] = $goods_id;
            $attr_titles = $request->post('attr_title');
            $attr_ids = $request->post('attr_id');
            $attr_values = $request->post('attr_value');
            foreach ($attr_titles as $key=>$value){
                $data['attr_title'] = $value;
                $data['attr_id'] = isset($attr_ids[$key])?$attr_ids[$key]:0;
                $data['value'] = $attr_values[$key];
                if(!$data['value']){
                    continue;
                }
                ShopGoodsAttributeModel::updateOrCreate(['attr_title'=>$value,'goods_id'=>$goods_id],$data);
            }
            ShopGoodsAttributeModel::where('goods_id',$goods_id)->whereNotIn('attr_title',$attr_titles)->delete();
        }else{
            ShopGoodsAttributeModel::where('goods_id',$goods_id)->delete();
        }
        ShopAttributeModel::init()->addOrEdit($request);
        return true;
    }

    public function handleSpec(Request $request,$goods_id)
    {
        if($request->post('spec')){
            ShopGoodsSpecModel::init()->where('goods_id',$goods_id)->delete();
            $where['goods_id'] = $data['goods_id'] = $goods_id;
            $spec = $request->post('spec');
            $spec_title = $request->post('spec_title');
            foreach ($spec as $id=>$value){
                $data['value'] = arr2str($value);
                if(is_numeric($id)){
                    $data['spec_id'] = $id;
                    $where['title'] = $data['title'] = $spec_title[$id];
                }else{
                    $specModel = new ShopSpecModel();
                    $specModel->type_id = $request->post('goods_type');
                    $specModel->title = $spec_title[$id];
                    $specModel->value = arr2str($value);
                    if($specModel->save()){
                        $spec_id =  $specModel ->id;
                    }else{
                        $spec_id  = 0;
                    }
                    $data['spec_id'] = $spec_id;
                    $where['title'] = $data['title'] = $spec_title[$id];
                }
                ShopGoodsSpecModel::updateOrCreate($where,$data);
            }

            if($request->post('goods_spec')){
                ShopGoodsSpecValueModel::init()->where('goods_id',$goods_id)->delete();
                unset($where,$data);
                $goods_spec = $request->post('goods_spec');
                $goods_spec_price = $request->post('goods_spec_price');
                $goods_spec_vip_price = $request->post('goods_spec_vip_price');
                $goods_spec_market_price = $request->post('goods_spec_market_price');
                $goods_spec_stock = $request->post('goods_spec_stock');
                $where['goods_id'] = $data['goods_id'] = $goods_id;
                foreach ($goods_spec as $key=>$item){
                    $data['sku_sn'] = SelfEncrypt::createCode('SKU');
                    $where['goods_spec_items'] = $data['goods_spec_items'] = $item;
                    $data['price'] = $goods_spec_price[$key];
                    $data['vip_price'] = $goods_spec_vip_price[$key];
                    $data['market_price'] = $goods_spec_market_price[$key];
                    $data['stock'] = $goods_spec_stock[$key];
                    ShopGoodsSpecValueModel::updateOrCreate($where,$data);
                }
            }
        }
    }

    public function editPrice(Request $request,$id)
    {
        $goods = self::find($id);
        $res = true;
        if($goods->goods_zone == 1){
            $res = ShopGoodsBillModel::init()->addPrice($request,$goods->goods_id);//特惠增值区
        }
        if($res){
            $this->handPrice($request,$goods);
            return $goods->save();
        }
        return false;
    }

    protected function handPrice(Request $request,ShopGoodsModel $goods)
    {
        $goods->price = $request->post('price',0);
        $goods->vip_price =  $goods->price;
//        $goods->vip_price = $request->post('vip_price',0);
        $goods->market_price = $request->post('market_price',0);
        $goods->cost_price = $request->post('cost_price',0);
        $goods->agent_price = $request->post('agent_price',0);
        $goods->xf_points_ratio = $request->post('xf_points_ratio',0);
    }

    protected function handleCategory($category_ids,ShopGoodsModel $goods)
    {
        $parent_id = 0;
        $parent_ids = '';
        if($category_ids){
            $pids = array_filter(str2arr($category_ids));
            if(is_array($pids)&&!empty($pids)){
                $parent_id = end($pids);
                $parent_ids = arr2str($pids);
            }elseif(!is_array($pids)&&!empty($pids)){
                $parent_id = $pids;
                $parent_ids = $pids;
            }
        }
        $goods->category_id = $parent_id;
        $goods->category_ids = ','.$parent_ids.',';
    }

    protected function setGoodsCode($goods_code,$zone)
    {
        $prefix = 'HS';
        if ($zone == 2){
            $prefix = 'TJ';
        }elseif ($zone == 3){
            $prefix = 'CJ';
        }
        return $goods_code?$goods_code:SelfEncrypt::createCode($prefix);
    }
}
